package com.college.userInfo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.page.PageMethod;
import com.college.common.constant.ExceptionCodeEnum;
import com.college.common.constant.SqlConstants;
import com.college.common.pojo.ao.UserInfo;
import com.college.common.pojo.dto.userInfo.*;
import com.college.common.pojo.model.page.PageParamRequest;
import com.college.common.pojo.vo.userInfo.UserInfoLoginVO;
import com.college.common.response.CommonResult;
import com.college.common.utils.http.RequestUtils;
import com.college.common.utils.log.LogPrintUtils;
import com.college.common.utils.nickName.NickNameUtils;
import com.college.common.utils.object.ObjectUtil;
import com.college.common.utils.password.PassWordUtils;
import com.college.userInfo.mapper.UserInfoMapper;
import com.college.userInfo.service.UserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 系统配置 服务实现类
 * </p>
 *
 * @author 小C工作室
 * @since 2022-05-31
 */
@Service
@Slf4j
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public List<UserInfo> queryList(QueryUserInfoDTO queryUserInfoDTO) {
        return userInfoMapper.queryList(queryUserInfoDTO);
    }

    @Override
    public List<UserInfo> queryListPage(QueryUserInfoDTO queryUserInfoDTO, PageParamRequest pageParamRequest) {
        PageMethod.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        return userInfoMapper.queryList(queryUserInfoDTO);
    }

    @Override
    public CommonResult<String> addUser(AddUserInfoDTO addUserInfoDTO) {
        return this.save(addUserInfoDTO)? CommonResult.success("用户新增成功") : CommonResult.failed("用户新增失败");
    }

    @Override
    public CommonResult<String> updateUser(UpdateUserInfoDTO updateUserInfoDTO) {
        UserInfo userInfo = ObjectUtil.objectCopyProperties(updateUserInfoDTO, UserInfo.class);
        //防止更新到账号密码
        userInfo.setPassword(null);
        userInfo.setUsername(null);
        return this.updateById(userInfo) ? CommonResult.success("用户修改成功") : CommonResult.failed("用户修改失败");
    }

    @Override
    public CommonResult<UserInfoLoginVO> login(UserInfoLoginDTO userInfoLoginDTO) {
        try {
            String username = userInfoLoginDTO.getUsername();
            String password = userInfoLoginDTO.getPassword();

            HttpServletRequest request = RequestUtils.getHttpServletRequest();
            if (ObjectUtils.isEmpty(request)) {
                return CommonResult.failed(ExceptionCodeEnum.UNAUTHORIZED, "用户登录异常");
            }
            // 通过账号获取后台用户
            LambdaQueryWrapper<UserInfo> lqw = new LambdaQueryWrapper<>();
            lqw.eq(UserInfo::getUsername, username)
                    .last(SqlConstants.LIMIT_1);
            UserInfo userInfo = this.getOne(lqw);

            if (ObjectUtils.isEmpty(userInfo)) {
                return CommonResult.failed(ExceptionCodeEnum.UNAUTHORIZED, "账号密码错误，请从重新登录");
            }

            String userInfoPassword = userInfo.getPassword();

            // 验证密码
            String encryptPassword = PassWordUtils.getEncryptPassword(password);
            if (Boolean.TRUE.equals(userInfoPassword.equals(encryptPassword))) {
                // 登录
                return CommonResult.success(this.loginUser(userInfo));
            }
            return CommonResult.failed(ExceptionCodeEnum.UNAUTHORIZED, "账号密码错误，请从重新登录");
        } catch (Exception e) {
            LogPrintUtils.info(log, "后台登录异常，具体异常：{}", e.getMessage());
            e.printStackTrace();
            return CommonResult.failed("后台登录异常");
        }
    }

    @Override
    public UserInfoLoginVO loginUser(UserInfo user) {
        UserInfoLoginVO userInfoLoginVO = new UserInfoLoginVO();

        // 封装返回参数
        user.setPassword("dashabi");
        userInfoLoginVO.setUserInfo(user);
        return userInfoLoginVO;
    }

    @Override
    public CommonResult<String> register(UserInfoRegisterDTO userInfoRegisterDTO) {
        String username = userInfoRegisterDTO.getUsername();
        String password = userInfoRegisterDTO.getPassword();
        int length = password.length();

        if (length < 8 || length > 16) {
            return CommonResult.failed("密码长度不正确，请输入8-16位的密码！");
        }

        LambdaQueryWrapper<UserInfo> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UserInfo::getUsername, username)
                .last(SqlConstants.LIMIT_1);
        UserInfo one = this.getOne(lqw);
        if (ObjectUtils.isNotEmpty(one)) {
            return CommonResult.failed("用户注册失败，请更换用户名重新注册！");
        }

        UserInfo userInfo = ObjectUtil.objectCopyProperties(userInfoRegisterDTO, UserInfo.class);
        // 加密密码
        String encryptPassword = PassWordUtils.getEncryptPassword(password);
        userInfo.setPassword(encryptPassword);
        userInfo.setNickName(NickNameUtils.getNickName());

        boolean result = Boolean.TRUE.equals(this.save(userInfo));
        if (Boolean.TRUE.equals(result)) {
            return CommonResult.success("用户注册成功");
        }
        return CommonResult.failed("用户注册失败");
    }

    /**
     * 更新用户密码
     *
     * @param userInfoLoginDTO 更新对象
     * @return 是否成功
     */
    @Override
    public CommonResult<String> updateLoginInfo(UserInfoLoginDTO userInfoLoginDTO) {
        String username = userInfoLoginDTO.getUsername();
        String password = userInfoLoginDTO.getPassword();
        int length = password.length();

        if (length < 8 || length > 16) {
            return CommonResult.failed("密码长度不正确，请输入8-16位的密码！");
        }

        LambdaQueryWrapper<UserInfo> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UserInfo::getUsername, username)
                .last(SqlConstants.LIMIT_1);
        UserInfo userInfo = this.getOne(lqw);
        if (ObjectUtils.isEmpty(userInfo)) {
            return CommonResult.failed("用户密码更新失败，请重新尝试！");
        }

        String encryptPassword = PassWordUtils.getEncryptPassword(password);
        userInfo.setPassword(encryptPassword);
        return this.updateById(userInfo) ? CommonResult.success("用户密码更新成功"):CommonResult.failed("用户密码更新失败");
    }
}
